# -*- coding: utf-8 -*-

"""
@Datetime: 2018/8/19
@Author: Zhang Yafei
"""
import json
import ssl
from fake_useragent import UserAgent
import requests
import config
import stations
from prettytable import PrettyTable

ua = UserAgent()

headers = {'User-Agent': ua.random}
#关闭证书的验证
# ssl._create_default_https_context = ssl._create_unverified_context

session = requests.Session()
session.headers = headers

with open('station.txt', 'r') as f:
    station = json.loads(f.read())


class Login():
    """实现12306的登录"""
    def __init__(self):
        self.capycha_url = 'https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&0.27575294592849064'
        self.capycha_check_url = 'https://kyfw.12306.cn/passport/captcha/captcha-check'
        self.login_url = 'https://kyfw.12306.cn/passport/web/login'

    def download_code(self):
        """1.下载验证码"""
        response = session.get(self.capycha_url)
        f = open('code.jpg','wb')
        f.write(response.content)
        f.close()
        self.check_code()

    def check_code(self):
        """2.检测验证码"""
        code = input("请输入验证码(x1 y1 x2 y2|103 150 176 149)：") #要去掉验证码头部30px左右
        data = {
            'answer': code.split(),
            'login_site': 'E',
            'rand': 'sjrand',
        }
        res = session.post(self.capycha_check_url,data=data)
        res_json = res.json()
        if res_json['result_code'] != '4':
            print("验证码错误")
            self.download_code()
        else:
            self.login()

    def login(self):
        """3.登录"""
        login_data = {
            'username': config.username,
            'password': config.password,
            'appid': 'otn',
        }
        result = session.post(self.login_url,data=login_data)
        print(result.text)
        with open('cookies.json','w') as f:
            json.dump(session.cookies.get_dict(),f)


class GetInfo():
    """查询列车相关信息"""
    def __init__(self,time,start,stop):
        self.time = time
        self.start = start
        self.stop = stop
        self.select_url = 'https://kyfw.12306.cn/otn/leftTicket/queryX?leftTicketDTO.train_date={0}&leftTicketDTO.from_station={1}&leftTicketDTO.to_station={2}&purpose_codes=ADULT'.format(self.time, self.start, self.stop)

    def get_list(self):
        response = session.get(self.select_url)
        info = response.json()
        infos = info['data']['result']
        # table = PrettyTable(['车次','始发站','出发站-到达站','终点站','出发时间-到达时间','历时', '商务特等座', '一等座','二等座', '高级软卧', '软卧', '硬卧', '硬座', '无座'])
        print("车次\t\t始发站\t出发站-到达站\t\t终点站\t出发时间-到达时间\t历时\t\t商务特等座\t一等座\t二等座\t高级软卧\t软卧\t\t硬卧\t\t硬座\t\t无座")
        for info in infos:
            i = info.split('|')
            checi = i[3]
            start_station = station[i[4]]
            if len(start_station) < 4:
                for a in range(4 - len(start_station)):
                    start_station = start_station + ' '
            stop_station = station[i[5]]
            if len(stop_station) < 4:
                for a in range(4 - len(stop_station)):
                    stop_station = stop_station + ' '
            start = station[i[6]]
            stop = station[i[7]]
            start_time = i[8]
            stop_time = i[9]
            time_long = i[10]
            if not checi.startswith('G'):
                ruanwo = i[23]
                yingzuo = i[29]
                yingwo = i[28]
                wuzuo = i[26]
                gruanwu = i[21]
                url = 'https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no={0}&from_station_no={1}&to_station_no={2}&seat_types={3}&train_date={4}'.format(i[2],i[16],i[17],i[35],self.time)
                try:
                    result = session.get(url).json()['data']
                except:
                    continue
                try:
                    ruanwo_price = result['A4']
                except KeyError:
                    ruanwo_price = '    '
                try:
                    gruanwu_price = result['A6']
                except Exception:
                    gruanwu_price = '    '
                try:
                    yingwo_price = result['A3']
                except:
                    yingwo_price = '    '
                try:
                    yingzuo_price = result['A1']
                except:
                    yingzuo_price = '    '
                wozuo_price = result['WZ']
                shangwu = shangwu_price = '    '
                yideng_price = yideng = '    '
                erdeng_price = erdeng = '    '
            else:
                shangwu = i[32]
                yideng = i[31]
                erdeng = i[30]
                url = 'https://kyfw.12306.cn/otn/leftTicket/queryTicketPrice?train_no={0}&from_station_no={1}&to_station_no={2}&seat_types={3}&train_date={4}'.format(i[2], i[16], i[17], i[35], self.time)
                try:
                    result = session.get(url).json()['data']
                except:
                    continue
                try:
                    shangwu_price = result['A9']
                except:
                    shangwu_price = '    '
                try:
                    yideng_price = result['M']
                except:
                    yideng_price = '    '
                erdeng_price = result['O']
                yingzuo = yingzuo_price = '    '
                ruanwo = ruanwo_price = '    '
                yingwo = yingwo_price = '    '
                gruanwu = gruanwu_price = '    '
                wuzuo = '    '
                wozuo_price = '    '

            print('{0:<5}\t{1:<5}\t{2:>3}-{3:<3}\t\t{4:<3}\t{5:<4}-{6:<4}\t\t{7:<4}\t{8:<4}\t\t{9:<8}{10:<8}{11:<4}\t{12:<2}\t\t{13:<2}\t\t{14:<2}\t\t{15:<2}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{16:<12}{17:<8}{18:<8}{19:<8}{20:<8}{21:<8}{22:<8}{23:<8}'.format(
                    checi, start_station, start,
                    stop, stop_station,
                    start_time, stop_time,
                    time_long,shangwu,yideng,erdeng, gruanwu, ruanwo, yingwo,yingzuo, wuzuo, shangwu_price,yideng_price,erdeng_price,gruanwu_price, ruanwo_price, yingwo_price, yingzuo_price, wozuo_price))

        #     table.add_row([checi, start_station, start+'-'+stop, stop_station, start_time+'-'+stop_time,
        #                    time_long, shangwu+'('+shangwu_price+')', yideng+'('+yideng_price+')',
        #                    erdeng+'('+erdeng_price+')', gruanwu+'('+gruanwu_price+')',
        #                    ruanwo+'('+ruanwo_price+')', yingwo+'('+yingwo_price+')', yingzuo+'('+yingzuo_price+')',
        #                    wuzuo+'('+wozuo_price+')'])
        # table.border = 0
        # print(table)
            # for a in i:
                # print('[{}]{}'.format(c,a))
                # c += 1
            # break


def station_code():
    # url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9002'
    station = {}
    for i in stations.station_names.split('@'):
        if i:
            re = i.split('|')
            station[re[1]] = re[2]
            station[re[2]] = re[1]
    with open('station.txt', 'w') as f:
        json.dump(station, f)


def main():
    """ 查询车次信息 """
    start = input('请输出出发地：')
    stop = input('请输入目的地：')
    time = input('请输入日期(xxxx-xx-xx)：')
    # start = '太原南'
    # stop = '北京'
    # time = '2018-10-07'

    """ 登录 """
    # get = Login()
    # get.download_code()

    """ 查询车票信息 """
    info = GetInfo(time,station[start],station[stop])
    info.get_list()


if __name__ == '__main__':
    main()
